package com.lezijie.seckill.controller;

import com.lezijie.seckill.pojo.User;
import com.lezijie.seckill.service.IGoodsService;
import com.lezijie.seckill.service.IUserService;
import com.lezijie.seckill.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 商品管理
 * @author 孙志鹏
 * @createDate 2021/10/26 19:13
 */
@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Resource
    private IUserService userService;
    @Autowired
    private IGoodsService goodsService;

    /**
     * 跳转到商品列表页面
     * @param model 跳转前端页面携带数据使用
     * @return 返回goodsList页面
     */
    @RequestMapping("/toList")
    public String toList(Model model, User user) {
        // if (!StringUtils.hasLength(ticket)) {
        //     return "/login";
        // }
        // // User user = (User) session.getAttribute(ticket);
        // User user = userService.getUserByCookie(ticket, request, response);
        // if (null == user) {
        //     return "/login";
        // }
        model.addAttribute("user", user);
        model.addAttribute("goodsList", goodsService.findByGoodsVo());
        return "/goodsList";
    }

    /**
     * 根据商品id查询详情
     * @param id 商品id
     * @param user 用户
     * @param model
     * @return 商品详情页面
     */
    @GetMapping("/toDetail/{goodsId}")
    public String toDetail(@PathVariable("goodsId") Long id, User user, Model model) {
        model.addAttribute("user",user);
        GoodsVo skillGoodsVo = goodsService.findGoodsById(id);
        Date startDate = skillGoodsVo.getStartDate();
        Date endDate = skillGoodsVo.getEndDate();
        Date nowDate = new Date();
        // 秒杀状态
        int seckillStatus = 0;
        // 秒杀倒计时
        int remainSeconds = 0;
        // 秒杀还未开始
        if (nowDate.before(startDate)) {
            remainSeconds = ((int) ((startDate.getTime() - nowDate.getTime())/1000));
        } else if (nowDate.after(endDate)) {
            // 秒杀已经结束
            seckillStatus = 2;
            remainSeconds = -1;
        } else {
            // 秒杀中
            seckillStatus = 1;
            remainSeconds = 0;
        }
        model.addAttribute("remainSeconds",remainSeconds);
        model.addAttribute("secKillStatus",seckillStatus);
        model.addAttribute("goods",skillGoodsVo);
        return "goodsDetail";
    }
}
